<template>
	<view class="App">
		<view class="loginStep1"  v-if="$util.isEmpty(wxUserInfo) && !loading">
			<view class="banner_box">
				<image :src="loginBgImg"></image>
			</view>
			<view class="login_form_wrap">
				<view class="login_form">
					<!-- <view class="login_tab">
						<view class="item" v-for="(item,index) in loginWay" :key="item"
							  :class="{on: activeIndex === index}" @click="switchTab(index)">
							<text>{{ item }}</text>
						</view>
					</view> -->
					<view class="input_wrap" v-show="activeIndex === 0">
						<view class="input_box mobile">
							<input type="number" placeholder="请输入您的手机号" :maxlength="11"
								   v-model="form.mobile" placeholder-class="login_pl">
						</view>
						<view class="input_box code">
							<input type="number" placeholder="请输入您的验证码" :maxlength="4"
								   v-model="form.code"  placeholder-class="login_pl">
							<view class="code_btn" @click="getVerificationCode">{{ isSend===1?countDown+'s':'获取验证码' }}
							</view>
						</view>
					</view>
					<!-- <view class="input_wrap" v-show="activeIndex === 1">
						<view class="input_box account">
							<input type="text" placeholder="请输入您的账号" v-model="form.account" placeholder-class="login_pl">
						</view>
						<view class="input_box pwd">
							<input type="text" :password="true" placeholder="请输入您的密码"
								   v-model="form.pwd" placeholder-class="login_pl">
						</view>
					</view> -->
					<view class="login_btn" :class="{on: canLogin}" @click="login">登录</view>
					<view class="tip"><text class="left">
                            登录注册表示我已同意
                        </text><navigator class="right" url="/pages/admin/servicesAgreement">
                            《用户服务协议》
                        </navigator></view>
				</view>
			</view>
				<!--  #ifdef MP-WEIXIN -->
				<!-- <view v-if="hasAuth" class="wxAuth_wrap" @click="wxInit">
					<image :src="`${imgUrl}login/wxLogo.png`"></image>
					<text>微信授权登录</text>
				</view> -->
				<button class="wxAuth buttonPlain" open-type="getUserInfo" @getuserinfo="wxInit" :plain="true" hover-class="none">
					<view class="wxAuth_wrap">
						<image :src="`${imgUrl}login/wxLogo.png`"></image>
						<text>微信授权登录</text>
					</view>
				</button>
				<!--  #endif -->
				</view>

			<view class="authed App_col" v-if="!$util.isEmpty(wxUserInfo) && !mobile && !loading">
				<view class="avatar">
					<image :src="wxUserInfo.avatarUrl"></image>
				</view>
				<view class="title">{{wxUserInfo.nickName}}</view>
				<view class="tip">亲，您已授权，快去{{ constant.oemSource == 1 ? '开店' : '获客' }}吧!</view>
				<get-phone-number dataSource="wxAuth" @cbFn="getPhoneNum">
					<view class="btn">{{ constant.oemSource == 1 ? '创建我的建材店铺' : '开启一键获客'}}</view>
				</get-phone-number>
        	</view>

				<view class="empty" v-show="loading"></view>
	</view>
</template>

<script>

import { wechatBack, checkLogin, loginAll, getCode } from '@/api/common'
import { wxLogin, postWxCode, getWxUserInfo, loginToRole } from '@/api/login'
import { mobileReg } from '@/utils/tools/validate'
import { loginParmas, getUrlHref } from '@/utils/common'
import qs from 'qs'
import { getBasicUser, getUser, resetAllUser, wxLoginFn } from '@/utils/auth'
import getPhoneNumber from '@/pages/components/getPhoneNumber'
import { mapState, mapMutations, mapActions } from 'vuex'
// import { Promise } from 'q'

export default {
	name: 'Login',
	components: {
		getPhoneNumber
	},
	data() {
		return {
			constant: this.$constant,
			// loginWay: ['手机号登录', '账号登录'],
			loginWay: ['手机号登录'],
			activeIndex: 0,
			form: {
				mobile: '',
				code: '',
				account: '',
				pwd: ''
			},
			imgUrl: this.$constant.imgUrl,
			countDown: 59,
			isSend: 0,
			timer: null,
			isWechat: false,
			options: null,
			callBackData: null,
			constant: this.$constant,
			loading: true,
			wxUserInfo: {},
			currentQuery: {},
			hasAuth: false,
			mobile: ''
		}
	},
	watch: {
		loading(val) {
			if (val) {
				uni.showLoading({
					title: '加载中...'
				})
			} else {
				uni.hideLoading()
			}
		}
	},
	computed: {
		...mapState({
			loginInfo: state => state.login.loginInfo
		}),
		canLogin() {
			const { mobile, code, account, pwd } = this.form
			return (mobile && code && this.activeIndex === 0) || (account && pwd && this.activeIndex === 1)
		},
		loginBgImg() {
			return this.$constant.oemObj.loginBgUrl
		}
	},
	onLoad(option) {
		resetAllUser()
		this.option = option

		uni.showLoading({
			title: '加载中...'
		})
		this.getAllConfig().then(() => {
			// 审核时操作 start ===
			if (!this.$util.shieldReview()) {
				console.info('审核中')
				this.form = {
					mobile: '18888888888',
					code: '1234'
				}
				this.login()
				return false
			}
			// 审核时操作 end ===
			// this.weChat()
			// #ifdef MP-WEIXIN
			// this.setAuthStatus()
			wxLoginFn()
			// #endif
			this.checkLoginType()
			this.mobile = uni.getStorageSync('wxMobile')
		})
	},
	methods: {
		...mapMutations(['setLoginInfo']),
		...mapActions(['getAllConfig']),
		checkLoginType() {
			const token = uni.getStorageSync('token')
			const wxMobile = uni.getStorageSync('wxMobile')
			// const loginType = uni.getStorageSync('loginType')
			if (token && wxMobile) {
			// if (loginType) {
				// if (loginType === 'h5') {
				this.weChat()
				// } else if (loginType === 'wx') {
				// 	this.wxInit()
				// }
			} else {
				this.loading = false
			}
		},
		getPhoneNum() {
			uni.getStorage({
				key: 'wxMobile',
				success: res => {
					this.mobile = res.data
					this.wxLogin()
				}
			})
		},
		setAuthStatus() {
			uni.getUserInfo({
				provider: 'weixin',
				success: () => {
					this.hasAuth = true
				},
				fail: () => {
					this.hasAuth = false
				}
			})
		},
		wxInit() {
			// uni.login({
			// 	provider: 'weixin',
			// 	success: res => {
			// 		uni.setStorageSync('code', res.code)
			// 		console.log(res.code, 'res.code')
			// 		postWxCode({ code: res.code }).then(subRes => {
			// 			const { openid, session_key, unionid } = subRes.data
			// 			this.setLoginInfo({
			// 				openid,
			// 				session_key,
			// 				unionid
			// 			})
			// wxLoginFn().then(subRes => {
			// 	console.log('subRes', subRes)

			uni.getUserInfo({
				provider: 'weixin',
				success: sSubRes => {
					this.getWxUserInfo(sSubRes.iv, sSubRes.encryptedData).then(res => {
						let data = this.loginInfo
						data.unionid = data.unionid ? data.unionid : this.wxUserInfo.unionId
						this.setLoginInfo(data)
						uni.getStorage({
							key: 'wxMobile',
							success: () => {
								this.wxLogin()
							},
							fail: () => {
								this.loading = false
							}
						})
					})
				},
				fail: () => {
					this.loading = false
				}
			})
			// })
			// 		})
			// 	}
			// })
		},
		getUserInfo(e) {
			if (e.mp.detail.errMsg === 'getUserInfo:fail auth deny' || !e.mp.detail.iv) {
				return
			}
			this.getWxUserInfo(e.detail.iv, e.detail.encryptedData).then(() => {
				uni.getStorage({
					key: 'wxMobile',
					success: () => {
						this.wxLogin()
					},
					fail: () => {
						this.loading = false
					}
				})
			})
		},
		getWxUserInfo(iv, encryptedData) {
			this.loading = true
			const params = {
				sessionKey: this.loginInfo.session_key,
				iv,
				encryptData: encryptedData
			}
			return getWxUserInfo(params).then(res => {
				const { avatarUrl, city, country, gender, language, nickName, province, unionId } = res.data
				this.wxUserInfo = { avatarUrl, city, country, gender, language, nickName, province, unionId }
			})
		},
		wxLogin(isType = false) {
			const params = {
				parent_id: '',
				phoneNumber: uni.getStorageSync('wxMobile'),
				userInfo: this.wxUserInfo,
				scopeSessions: this.loginInfo
			}
			this.currentQuery = JSON.parse(uni.getStorageSync('currentQuery'))
			if (this.currentQuery.share_user_id) {
				params.parent_id = this.currentQuery.share_user_id
			}
			// 员工推荐活动新增推荐id
			if (this.currentQuery.recommend_admin_id) {
				params.recommend_admin_id = this.currentQuery.recommend_admin_id
			}
			wxLogin(params).then(res => {
			 uni.setStorageSync('loginType', 'wx')
			 uni.setStorage({
				 key: 'token',
				 data: res.data,
				 success: () => {
					 	checkLogin().then(subRes => {
							this.setLoginToRole(subRes.data).then(returnData => {
								const { user_id, token, role_id } = returnData
								const { type, subscribe } = subRes.data
								uni.setStorageSync('user_id', user_id)
								uni.setStorageSync('token', token)
								uni.setStorageSync('role_id', role_id)

								// 审核时跳转地址不同 -start
								if (!this.$util.shieldReview()) {
									uni.redirectTo({
										url: `/pages/getGuest/index?owner_user_id=${user_id}`
									})
									return false
								}
								// 审核时跳转地址不同 -end

								// uni.setStorageSync('subscribe', subscribe)
								if (type === 'upgrade') {
									const query = loginParmas(this.option)
									// this.loading = false
									let source = this.$constant.oemSource
									let sourceRoleId = source == 1 ? '2' : '1'
									// let storageRoleId = uni.getStorageSync('storageRoleId')
									let storageRoleId = this.option.roleId
									let roleId = storageRoleId || sourceRoleId
									let jumpUrl = ''
									if (source == 1) {
										jumpUrl = `/pages/login/loginCity/index${this.$util.parse({
											role: roleId,
											...query
										})}`
									} else if (source == 2 || source == 4) {
										jumpUrl = `/pages/login/loginCity/index${this.$util.parse({
											role: roleId,
											...query
										})}`
									} else {
										jumpUrl = `/pages/login/loginIdentity/index${this.commonJS.queryData(query)}`
									}

									uni.navigateTo({
										url: jumpUrl
									})
									return
								}

								if (type === 'login' || isType) {
									const params = {
										owner_user_id: user_id,
										share_user_id: user_id,
										user_id: user_id
									// token: token,
									// type: 'hkds_miniapp'
									}

									// 跳转webview --------------------
									// const returnUrl = encodeURIComponent(`${this.$constant.formal}/hkds/#/admin/guest${this.$util.parse(params)}`)
									// uni.navigateTo({
									// 	url: `/pages/page/webview/index?returnUrl=${returnUrl}&user_id=${user_id}`
									// })
									// 跳转原生页面 --------------------
									let loginReturnUrl = uni.getStorageSync('loginReturnUrl')
									if (loginReturnUrl) {
										uni.removeStorageSync('loginReturnUrl')
										console.log('asdfadsf', loginReturnUrl)
										uni.redirectTo({
											url: this.$util.spliceUrl(`${loginReturnUrl}`, `owner_user_id=${user_id}`)
										})
									} else {
										if (role_id == 2) {
											uni.redirectTo({
												url: `/pages/design/material/index${this.$util.parse(params)}`
											})
										} else {
											uni.redirectTo({
												url: `/pages/getGuest/shareIndex${this.$util.parse(params)}`
											})
										}
									}
								}
						 	})
						}).catch(() => {
							uni.removeStorageSync('token')
						})
				 }
			 })
			})
		},
		switchTab(index) {
			this.activeIndex = index
		},
		login() {
			if (!this.canLogin) {
				return
			}
			// 登录
			/**
                 * query 参数
                 * p_share_user_id
                 * share_user_id
                 * owner_user_id
				 * recommend_admin_id //员工推荐活动新增推荐id
                 * f
                 */
			const form = {}
			if (!this.$util.isEmpty(this.callBackData) && !this.$util.isEmpty(this.callBackData.type)) {
				form.type = this.callBackData.type
			}
			if (!this.$util.isEmpty(this.callBackData) &&
                    !this.$util.isEmpty(this.callBackData.unionid)) {
				form.unionid = this.callBackData.unionid
			}
			loginAll({
				mobile: this.form.mobile,
				code: this.form.code,
				...this.fomatQuery(),
				...form
			}).then((res) => {
				uni.setStorageSync('loginType', 'h5')
				uni.setStorageSync('wxMobile', this.form.mobile)
				this.loginSucceed(res.data, true)
				this.isWechat = true
			})
		},
		getVerificationCode() {
			uni.showLoading({
				title: '',
				mask: true
			})

			if (this.isSend === 1) {
				return
			}
			if (mobileReg.test(this.form.mobile)) {
				getCode({
					mobile: this.form.mobile
				}).then((res) => {
					uni.hideLoading()
					if (res.status === 'success') {
						this.form.code = res.data.result.code || ''
						this.isSend = 1
						this.beginCountDown()
					} else {
						uni.showToast({
							title: res.errors.message,
							icon: 'none',
							mask: true
						})
					}
				})
			} else {
				uni.showToast({
					title: '请输入正确的手机号',
					icon: 'none',
					mask: true
				})
			}
		},
		beginCountDown() {
			this.countDown = 59
			this.timer = setInterval(() => {
				if (this.countDown === 0) {
					clearInterval(this.timer)
					this.isSend = 2
					return
				}
				this.countDown -= 1
			}, 1000)
		},
		weChat() {
			// #ifdef H5
			if (this.option.type === 'wechat' && this.option.code && this.option.state) {
				this.callBack()
			} else if (process.env.NODE_ENV === 'production') {
				const startUrl = getUrlHref()
				window.open(`${startUrl}/apihkds/api/oauth/code${this.$util.parse({
					...this.option,
					type: 'wechat'
				})}`)
			}
			// #endif
			this.checkLogin()
		},
		callBack() {
			wechatBack({
				...this.fomatQuery(),
				type: this.option.type,
				code: this.option.code,
				state: this.option.state
			})
				.then((res) => {
					if (res.data.login === 1) {
						uni.setStorageSync('token', res.data.token)
						this.checkLogin()
					} else {
						this.callBackData = res.data
						this.isWechat = true
					}
				})
		},
		fomatQuery() {
			const query = {}
			const arr = ['owner_user_id', 'share_user_id', 'f', 'p_share_user_id', 'recommend_admin_id']
			Object.keys(this.option).forEach((i) => {
				if (arr.includes(i)) {
					query[i] = this.option[i]
				}
			})
			return query
		},

		checkLogin() {
		  checkLogin().then((res) => {
		      this.loginSucceed(res.data, true)
		  }).catch(() => {
				this.loading = false
				this.isWechat = true
				uni.removeStorageSync('token')
		  })
		},
		// 强制转换角色
		async setLoginToRole(data = {}) {
			let returnData = {}
			if (data.token) {
				uni.setStorageSync('token', data.token)
				if (this.$constant.oemSource == 1 || this.$constant.oemSource == 4) {
					let role_id = this.$constant.oemSource == 1 ? '2' : '1'
					await loginToRole({ role_id: role_id }).then(res => {
						returnData = res.data
					}).catch(e => {
						returnData = data
					})
				} else {
					returnData = data
				}
				return returnData
			} else {
				uni.redirectTo({
					url: `/pages/page/login/index${this.$util.parse(this.option)}`
				})
				return {}
			}
		},
		loginSucceed(res, isType = false) {
			this.setLoginToRole(res).then(data => {
				uni.setStorageSync('user_id', data.user_id)
				uni.setStorageSync('token', data.token)
				uni.setStorageSync('role_id', data.role_id)
				// uni.setStorageSync('subscribe', data.subscribe)
				uni.removeStorageSync('basicUser')
				uni.removeStorageSync('userInfo')
				// 审核时跳转地址不同 -start
				if (!this.$util.shieldReview()) {
					uni.redirectTo({
						url: `/pages/getGuest/index?owner_user_id=${data.user_id}`
					})
					return false
				}
				// 审核时跳转地址不同 -end
				if (!this.$util.isEmpty(res.type) && res.type === 'upgrade') {
					const query = loginParmas(this.option)
					// this.loading = false

					let source = this.$constant.oemSource
					let sourceRoleId = source == 1 ? '2' : '1'
					// let storageRoleId = uni.getStorageSync('storageRoleId')
					let storageRoleId = this.option.roleId
					let roleId = storageRoleId || sourceRoleId
					let jumpUrl = ''
					if (source == 1) {
						jumpUrl = `/pages/login/loginCity/index${this.$util.parse({
							role: roleId,
							...query
						})}`
					} else if (source == 2 || source == 4) {
						jumpUrl = `/pages/login/loginCity/index${this.$util.parse({
							role: roleId,
							...query
						})}`
					} else {
						jumpUrl = `/pages/login/loginIdentity/index${this.commonJS.queryData(query)}`
					}

					uni.navigateTo({
						url: jumpUrl
					})
					return
				}
				if ((!this.$util.isEmpty(data.type) && data.type === 'login') || isType) {
					const params = {
						owner_user_id: data.user_id,
						share_user_id: data.user_id,
						user_id: data.user_id
					// token: data.token,
					// type: 'hkds_miniapp'
					}
					clearInterval(this.timer)

					// uni.redirectTo({
					// 	url: `/pages/design/designerIndex?${qs.stringify(params)}`
					// })

					// 跳转webview --------------------
					// const returnUrl = encodeURIComponent(`${this.$constant.formal}/hkds/#/admin/guest${this.$util.parse(params)}`)
					// uni.navigateTo({
					// 	url: `/pages/page/webview/index?returnUrl=${returnUrl}&user_id=${data.user_id}`
					// })
					// 跳转原生页面 --------------------
					let loginReturnUrl = uni.getStorageSync('loginReturnUrl')
					if (loginReturnUrl) {
						uni.removeStorageSync('loginReturnUrl')
						uni.redirectTo({
							url: this.$util.spliceUrl(`${loginReturnUrl}`, `owner_user_id=${data.user_id}`)
						})
					} else {
						if (data.role_id == 2) {
							uni.redirectTo({
								url: `/pages/design/material/index${this.$util.parse(params)}`
							})
						} else {
							uni.redirectTo({
								url: `/pages/getGuest/shareIndex${this.$util.parse(params)}`
							})
						}
					}

					// uni.navigateTo({
					// 	url: `/pages/page/webview/index?user_id=${data.user_id}`
					// })

					// uni.navigateTo({
					// 	url: `/pages/design/material/index${this.$util.parse(params)}`
					// })

					// uni.navigateTo({
					// 	url: `/pages/design/designerIndex${this.$util.parse(params)}`
					// })

					// uni.navigateTo({
					// 	url: `/pages/design/designCompany/indexNew${this.$util.parse(params)}`
					// })
					// uni.navigateTo({
					// 	url: `/pages/design/designCompany/indexNew${this.$util.parse(params)}`
					// })

				// switch (data.role_id) {
				// 	case 1:
				// 		uni.redirectTo({
				// 			url: `/pages/design/designCompany/indexNew${this.$util.parse(params)}`
				// 		})
				// 		break
				// 	case 3:
				// 		uni.redirectTo({
				// 			url: `/pages/design/designerIndex?${qs.stringify(params)}`
				// 		})
				// 		break
				// 	default:
				// 		uni.redirectTo({
				// 			url: `/pages/page/webview/index`
				// 		})
				// 		break
				// }
				}
			})
		}
	}
}
</script>

<style scoped lang="scss">

 .authed {
	 	box-sizing: border-box;
    padding-top: 220px;
	min-height: 100vh;
	background-color: #fff;
        .avatar {
            width: 160px;
            height: 160px;
            border-radius: 50%;
            overflow: hidden;
            image {
                width: 100%;
                height: 100%;
            }
        }
		 .title {
            margin-top: 31px;
        text-align: center;
        font-size:48px;
        font-weight:600;
        color:rgba(57,27,6,1);
    }
      .tip {
        font-size:36px;
        color: #999;
		margin-top: 108px;
    }
	  .btn {
        position: fixed;
        left: 0;
        right: 0;
        bottom: 190px;
        margin: auto;
        width: calc(100vw - 100px);
        height:100px;
        line-height: 100px;
        text-align: center;
        background:rgba(255,209,26,1);
        border-radius:50px;
        font-size:36px;
        font-weight:600;
        color:rgba(58,27,4,1);
    }

    }
.empty {
	width: 100%;
	width: 100vw;
	height: 100%;
	height: 100vh;
	background-color: #fff;
	position: fixed;
	z-index: 1000;
}
.wxAuth_wrap {
	position: fixed;
	left: 50%;
	transform: translateX(-50%);
	bottom: 98px;
	display: flex;
	flex-direction: column;
	align-items: center;
	image {
		width: 98px;
		height: 98px;
	}
	text {
		font-size:28px;
		color:rgba(51,51,51,1);
		line-height: 1;
		margin-top: 14px;
	}
}
.buttonPlain{
    border: none !important;
    padding: 0;
    margin: 0;
    width: auto;
    height: auto;
}

	.banner_box {
		height: 250px;
		// height:300px;

		image {
			width: 100%;
			height: 100%;
		}
	}

	.login_form_wrap {
		width: 100%;
		padding: 21px 70px 0;
		// position: absolute;
		// left: 50%;
		// top: 169px;
		// transform: translateX(-50%);
		box-sizing: border-box;

		.login_form {
			// padding: 50px 50px 40px;
			background: rgba(255, 255, 255, 1);
			// box-shadow: 0px 1px 21px 0px rgba(78, 78, 78, 0.15);
			// border-radius: 20px;

			.login_tab {
				padding: 0 54px 0 37px;
				display: flex;
				// justify-content: space-between;
				justify-content: center;

				.item {
					font-size: 32px;
					color: rgba(153, 153, 153, 1);
					position: relative;

					&.on {
						font-weight: 600;
						color: rgba(51, 51, 51, 1);

						&::before {
							content: '';
							position: absolute;
							left: 50%;
							bottom: -20px;
							transform: translateX(-50%);
							width: 50px;
							height: 6px;
							background: rgba(255, 209, 25, 1);
							border-radius: 3px;
						}
					}
				}
			}

			.login_btn {
				width: 100%;
				height: 100px;
				line-height: 100px;
				text-align: center;
				opacity: 0.9;
				border-radius: 50px;
				margin-top: 30px;
				font-size: 36px;
				font-weight: 600;
				border: 0 none;
				appearance: none;
				color: #fff;
				background: rgba(204, 204, 204, 1);

				&.on {
					background: rgba(255, 209, 25, 1);
					color: rgba(58, 27, 4, 1);
				}
			}
			.tip {
				line-height: 1;
				margin-top: 50px;
				text-align: center;
				font-size: 28px;
				.left {
					color: #999;
				}
				.right {
					display: inline;
					color: #3A1B04;
				}
			}
		}
	}

	.input_wrap {

		.input_box {
			display: flex;
			align-items: center;
			height: 100px;
			padding-left: 82px;
			border:1px solid rgba(221,221,221,1);
			opacity:0.9;
			border-radius:50px;
			background-repeat: no-repeat;
			background-position: 31px center;
			background-size: 40px 40px;

			&.mobile {
				background-image: url($imgUrl+'login/mobile.png');
			}

			&.code {
				background-image: url($imgUrl+'login/code.png');
				margin-top: 30px;
			}

			&.account {
				background-image: url($imgUrl+'login/account.png');
			}

			&.pwd {
				background-image: url($imgUrl+'login/pwd.png');
			}

			input {
				display: block;
				flex: 1;
				height: 40px;
				line-height: 40px;
				font-size: 30px;
				.login_pl {
					font-size: 34px;
					color: rgba(204, 204, 204, 1);
				}
			}

			.code_btn {
				padding: 0 42px;
				height: 70px;
				text-align: center;
				line-height: 70px;
				// border: 1px solid rgba(204, 204, 204, 1);
				// opacity: 0.9;
				// border-radius: 35px;
				font-size: 28px;
				color: rgba(51, 51, 51, 1);
				appearance: none;
			}
		}
	}

</style>
